﻿using System;
using System.Text;

namespace FallingRox
{
    public class ConsoleRenderer : IRenderer
    {
        readonly int renderRows;
        readonly int renderCols;
        readonly char[,] renderMatrix;

        public ConsoleRenderer(int screenRows, int screenCols)
        {
            this.renderMatrix = new char[screenRows, screenCols];

            this.renderRows = screenRows;
            this.renderCols = screenCols;

            this.ClearQueue();
        }

        //Enqueueing object for Rendering
        public void ForRendering(IRenderable obj)
        {
            char[,] image = obj.GetImage();

            int imgRows = image.GetLength(0);
            int imgCols = image.GetLength(1);

            MatrixCoords topLeft = obj.GetPosition();

            int lastRow = Math.Min(topLeft.Row + imgRows, this.renderRows);
            int lastCol = Math.Min(topLeft.Col + imgCols, this.renderCols);

            for (int row = topLeft.Row; row < lastRow; row++)
            {
                for (int col = topLeft.Col; col < lastCol; col++)
                {
                    if (row >= 0 && row < renderRows && col >= 0 && col < renderCols)
                    {
                        renderMatrix[row, col] = image[row - topLeft.Row, col - topLeft.Col];
                    }
                }
            }
        }

        //Rendering everything on the console
        public void RenderAll()
        {
            Console.SetCursorPosition(0, 0);
            StringBuilder frame = new StringBuilder();

            for (int row = 0; row < this.renderRows; row++)
            {
                for (int col = 0; col < this.renderCols; col++)
                {
                    frame.Append(this.renderMatrix[row, col]);
                }
                frame.Append(Environment.NewLine);
            }
            Console.WriteLine(frame.ToString());
        }

        //Clearing the queue
        public void ClearQueue()
        {
            for (int row = 0; row < this.renderRows; row++)
            {
                for (int col = 0; col < this.renderCols; col++)
                {
                    this.renderMatrix[row, col] = ' ';
                }
            }
        }
    }
}
